//
//  MTMineTaskViewController.swift
//  MT
//
//  Created by ooops on 2020/5/23.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import JXPagingView
import JXCategoryView
import YPNavigationBarTransition
import JXSegmentedView
import JMessage
import RxSwift

class MTJoinTaskViewController: BaseViewController {
    
    var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    private lazy var defaultImage: UIImage? = UIImage(named: defaultPlaceholderIcon60x60)
    
    fileprivate var isConnecting = false
    fileprivate var showNetworkTips = false
    private lazy var partyProvider: MTProvider<MTCreateTaskAPI> = {
        let provider = MTProvider<MTCreateTaskAPI>()
            //MTProvider<MTCreateTaskAPI>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private var result: [MTPartyTaskListInfoModel] = []
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    private var loadType: Int = 1
    private var clubType: MTPartyListTaskType = .joinTask
    
    convenience init(taskType: MTPartyListTaskType) {
        self.init()
        self.clubType = clubType
    }
    
    override func refreshView() {
        loadFirst()
    }
    
    /// 筛选聚会任务类型
    private var filterType: MTFilterPartyTaskType = MTFilterPartyTaskType.none

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.theme.background
        view.addSubview(friendRequestView)
        view.addSubview(tableView)
        
        friendRequestView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(NavigationBarHeight + StatusBarHeight)
            make.height.equalTo(64)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(friendRequestView.snp.bottom)
        }
        loadFirst()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        queryNotifyCount()
    }
    
    
    /// 过滤任务类型数据
    /// - Parameter filterType: filterType description
    func filterPartyTaskData(_ filterType: MTFilterPartyTaskType = MTFilterPartyTaskType.none) {
        self.currentPage = 1
        self.filterType = filterType
        loadData(loadMore: false)
    }
    
    @objc private func loadFirst() {
        self.currentPage = 1
        loadData(loadMore: false)
    }
    
    private func queryNotifyCount() {
        MTCreateTaskTool.queryNofityCount(provider: partyProvider, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if let m = model, m.code == 200, let count = m.result {
                weakSelf.friendRequestView.setRedPoint(pointValue: count)
            }
        }) { (_) in
            
        }
    }
    
    // MARK: - 加载数据
    /// - Parameter loadMore: 是否加载更多
    private func loadData(loadMore: Bool) {
        var queryParam: [String : Any] = ["curPage" : currentPage, "pageSize" : 10, "type" : self.clubType.rawValue]
        
        if filterType != MTFilterPartyTaskType.none {
            MBProgressHUD_JChat.showLoading(self.view)
            queryParam.updateValue(filterType.rawValue, forKey: "subType")
        }
        
        MTCreateTaskTool.queryPartyList(provider: partyProvider, parameters: queryParam, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            MBProgressHUD_JChat.dismiss(weakSelf.view)
            weakSelf.comporseData(model: model, loadMore: loadMore)
        }) { [weak self] (_) in
            guard let weakSelf = self else { return }
            MBProgressHUD_JChat.dismiss(weakSelf.view)
        }
    }
    
    private func comporseData(model: MTPartyListModel?, loadMore: Bool) {
        weak var weakSelf = self
        weakSelf?.tableView.mj_footer?.endRefreshing()
        weakSelf?.tableView.mj_header?.endRefreshing()
        if weakSelf?.currentPage == 1 {
            weakSelf?.tableView.mj_footer?.state = .idle
        }
        
        if let m = model {
            debugPrint("message: ", m.message ?? "")
            if let r = m.result {
                if (m.page?.pages == weakSelf?.currentPage) {
                    weakSelf?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }
                if loadMore == true {
                    weakSelf?.result = weakSelf!.result + r
                } else {
                    weakSelf?.result = r
                }
                
                weakSelf?.hiddenHF(isHidden: weakSelf?.result.count == 0)
            } else {
                weakSelf?.hiddenHF(isHidden: true)
            }
            
            DispatchQueue.main.async {
                weakSelf?.tableView.reloadData()
            }
        }
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadData(loadMore: true)
        
    }
    
    lazy var friendRequestView: MTDiscoverFriendRequestView = {
        let r: MTDiscoverFriendRequestView = MTDiscoverFriendRequestView(title: "待处理请求", subTitle: "聚会任务验证消息", type: .group)
//        r.backgroundColor = UIColor(hex: 0xf6f6f6)
        r.delegate = self
        return r
    }()
    
    fileprivate lazy var errorTips: JCNetworkTipsCell = JCNetworkTipsCell()

    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(MTJoinTaskCell.self, forCellReuseIdentifier: MTJoinTaskCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.backgroundColor = UIColor(hex: 0xf4f4f4)
        table.showsVerticalScrollIndicator = false
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        table.mj_footer?.ignoredScrollViewContentInsetBottom = 25
        table.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadFirst()

        }
        return table
    }()
}

extension MTJoinTaskViewController: MTDiscoverFriendRequestViewDelegate {
    
    func didTapFriendRequestEntrance() {
        self.friendRequestView.setRedPoint(pointValue: 0)
        let vc: MTPartyInviteInfoViewController = MTPartyInviteInfoViewController()
        self.navigationVC?.pushViewController(vc, animated: true)
    }
    
}


extension MTJoinTaskViewController: UITableViewDataSource, UITableViewDelegate {
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.result.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: MTJoinTaskCell = tableView.dequeueReusableCell(withIdentifier: MTJoinTaskCell.reuseIdentity(), for: indexPath) as! MTJoinTaskCell
        let model = self.result[indexPath.row]
        cell.model = model
        return cell
    }
    
    public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//        guard let cell = cell as? JCConversationCell else {
//            return
//        }
//        cell.bindConversation(datas[showNetworkTips ? indexPath.row - 1 : indexPath.row])
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 160
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.result[indexPath.row]
        if model.status == .ended {
            MBProgressHUD_JChat.show(text: "聚会任务已结束", view: self.view, 1)
            return
        }
        guard let pushId = model.id else { return }
        let vc = MTPartyTaskDetailViewController(partyTaskId: pushId)
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - network tips
extension MTJoinTaskViewController {
    
    
}


extension MTJoinTaskViewController: JXSegmentedListContainerViewListDelegate {
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        listViewDidScrollCallback = callback
    }


    func listView() -> UIView {
        return self.view
    }

    func listScrollView() -> UIScrollView {
        return UIScrollView()
    }
}

